package com.sds.session.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sds.servlet.vo.HeaderVO;
import com.sds.session.service.UserSessionService;

@Controller
public class LoginController {

	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private UserSessionService userSessionService;
	
	@ModelAttribute
	public HeaderVO headerVO(HttpServletRequest request, HttpServletResponse response) {
		HeaderVO headerVO = new HeaderVO();
		headerVO.setType("session");
		headerVO.setSessionId(request.getSession().getId());
		headerVO.setUserId(request.getParameter("userId"));
		return headerVO;
	}
	
	@RequestMapping("/login.do")
    public ModelAndView loginProcess(@ModelAttribute HeaderVO headerVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(StringUtils.isEmpty(headerVO.getUserId())) return null;
		
		userSessionService.createSession(headerVO.getUserId(), request.getRemoteAddr());

		ModelAndView mav = new ModelAndView("session/session_info");
		mav.addObject("headerVO", headerVO);
		mav.addObject("message", "Session Info Page");
		
		return mav;
    }
	
	@RequestMapping("/loginCheck.do")
	public ModelAndView checkLoginProcess(@ModelAttribute HeaderVO headerVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(StringUtils.isEmpty(headerVO.getUserId())) return null;
		
		boolean loginCheck = userSessionService.checkSession(headerVO.getUserId(), request.getRemoteAddr());
		
		ModelAndView mav = new ModelAndView("session/session_info");
		mav.addObject("headerVO", headerVO);
		mav.addObject("message", "Session Info Page");
		if( loginCheck )
			return mav;
		return null;
	}
}
